package com.jwater.gateway.common;

import jwater.org.springframework.util.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;

/**
 * @description:
 * @author: jnner
 * @createDate: 2021/3/27
 * @version: 1.0
 */
public class CommonGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
        if (route == null) {
            return chain.filter(exchange);
        }
        String destWsUrl = exchange.getAttribute("_destWsUrl_");
        if (!StringUtils.isEmpty(destWsUrl)) {
            return chain.filter(exchange);
        }

        String destUrl = exchange.getAttribute("_destUrl_");
        if (StringUtils.isEmpty(destUrl)) {
            return chain.filter(exchange);
        }
        exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR, URI.create(destUrl));
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1000000;
    }
}
